var uart = require('uart');
var iot = require('iot');

var network = require('network');

var net = network.openNetWorkClient();

/** 获取网络类型
* 目前支持两种类型：wifi cellular（蜂窝网）
*/
var type = net.getType();
console.log('________>>>>>>>>>> net type is: ' + type);

/** 获取网络状态
* 目前支持两种状态：connect disconnect（蜂窝网）
*/
var status = net.getStatus();
console.log('________>>>>>>>>>> net status is: ' + status);

var device;

//编写一个TCP 测试函数
function iot_test(){
	
	console.log('________>>>>>>>>>>start iot');

	var productKey = 'a14evgr26p4';
	var deviceName = 'testLED01';
	var deviceSecret = 'cb48e15a0d2e312212f391cf4aa8c9e4';

	var lightSwitch = 0;

	device = iot.device({
		productKey: productKey,
		deviceName: deviceName,
		deviceSecret: deviceSecret,
		region: 'cn-shanghai',
		success: function () {
			console.log('connect success');
			onConnect();
		},
		fail: function () {
			console.log('connect failed');
		}
	});

	function onConnect() {
		setInterval(function () {
			/** post properties */
			lightSwitch = 1 - lightSwitch;
			device.postProps({
				payload: {
					LightSwitch: lightSwitch
				},
				success: function () {
					console.log('postProps success');
				},
				fail: function () {
					console.log('postProps failed');
				}
			});
			/** post events */
			device.postEvent({
				id: 'Error',
				params: {
					ErrorCode: 0
				},
				success: function () {
					console.log('postEvent success');

				},
				fail: function () {
					console.log('postEvent failed');
				}
			});
		}, 3000);
	}

	device.on('connect', function () {
		console.log('(re)connected');
	});

	/* 网络断开事件 */
	device.on('disconnect', function () {
		console.log('disconnect ');
	});

	/* 关闭连接事件 */
	device.on('close', function () {
		console.log('iot client just closed');
	});

	/* 发生错误事件 */
	device.on('error', function (err) {
		console.log('error ' + err);
	});

	/* 云端设置属性事件 */
	device.on('props', function (payload) {
		console.log('cloud req data is ', payload);
		//console.log('LightSwitch ', payload.LightSwitch ? 'ON' : 'OFF');
		//收到云端设置门磁报警状态，重新上传
		if(payload.door_warn != null)
		{
			device.postProps({
				payload: {
					door_warn: payload.door_warn
				},
				success: function () {
					console.log('postProps success');
				},
				fail: function () {
					console.log('postProps failed');
				}
			});
		}
	});

	/* 云端下发服务事件 */
	device.on('service', function (id, payload) {
		console.log('received cloud serviceid is ' + id);
		console.log('received cloud req_data is ' + payload);
	});
}

//判断一下当前蜂窝网络是否连接
if (status == 'connect') {
	//如果已经连接，直接调用iot_test
    iot_test();
} else {
	//设置事件，如果收到蜂窝网络连接事件，调用iot_test函数
    net.on('connect', function() {
        iot_test();
    })
}

//如果蜂窝网络断开连接，打印日志
net.on('disconnect', function(){
    console.log('________>>>>>>>>>> device is disconnect');
});


var i2c = require('i2c');

var sensor = i2c.open({
  id: 'I2C2'
});

var msgbuf = [0];
function sensor_Test(){
 
	/*
	读出来两个字节，第1个是温度、第2个是湿度
	*/
	var regval = sensor.read(2);
	console.log('read sensor temp is ' + regval[0] + ' humidity is ' + regval[1]/255);
	
	//这里把数据上传到物联网云平台
	device.postProps({
		payload: {
			//温度
			temperature: regval[0],
			//湿度
			Humidity: regval[1]/255
		},
		success: function () {
			console.log('postProps success');
		},
		fail: function () {
			console.log('postProps failed');
		}
	});
}

setInterval(sensor_Test, 1000);

// user uart
var serial = uart.open({
  id: 'UART2'
});

console.log('start uart test');


// user uart data receive 
serial.on('data', function(data) {
  console.log('uart receive data is ' + data);
  
  //上传门磁报警状态
  device.postProps({
		payload: {
			door_warn: 1
		},
		success: function () {
			console.log('postProps success');
		},
		fail: function () {
			console.log('postProps failed');
		}
	});
});

// uart close
// serial.close();